package com.yan.utils;

import java.io.StringWriter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.CompactWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.yan.jwt.YbfUserBase;

/**
 * <p>
 * 功 能：一比分资料库
 * </p>
 * <p>
 * 描 述：XML格式数据转换工具类
 * </p>
 * <p>
 * 公 司：深圳华海乐盈网络科技有限公司
 * </p>
 * <p>
 * 版 权：Copyright (c) 2016
 * </p>
 * <p>
 * 创建时间：2016年6月27日 下午3:10:12
 * </p>
 * 
 * @author WangJian
 * @version 1.0
 */
public class XmlUtil {
	private static XStream xstream;

	static {
		xstream = new XStream(new DomDriver("UTF-8"));
	}

	/**
	 * 以压缩的方式输出XML
	 * 
	 * @param obj
	 * @return
	 */
	public static String toCompressXml(Object obj) {
		// 识别obj类中的注解
		xstream.processAnnotations(obj.getClass());
		StringWriter sw = new StringWriter();
		xstream.marshal(obj, new CompactWriter(sw));
		return sw.toString();
	}

	/**
	 * 以格式化的方式输出XML
	 * 
	 * @param obj
	 * @return
	 */
	public static String toXml(Object obj) {
		// 识别obj类中的注解
		xstream.processAnnotations(obj.getClass());
		return xstream.toXML(obj);
	}

	/**
	 * 转换成JavaBean
	 * 
	 * @param xmlStr
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T toBean(String xmlStr, Class<T> cls) {
		// 识别cls类中的注解
		xstream.processAnnotations(cls);
		T t = ((T) xstream.fromXML(xmlStr));
		return t;
	}

	public static void main(String args[]) {
		
		YbfUserBase ybfUserBase = new YbfUserBase();
		ybfUserBase.setId("1");
		ybfUserBase.setNickName("nickName");
		System.out.println(toCompressXml(ybfUserBase));
		System.out.println(toXml(ybfUserBase));
		
	//	toXml(ybfUserBase),YbfUserBase.class
		System.out.println(toBean(toXml(ybfUserBase),YbfUserBase.class));
	}
}


